package com.tanhua.server.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.server.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Value("${tanhua.secret}")
    private String secret;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        //如果本次请求中没有携带token，返回401状态码
        if (token == null) {
            response.setStatus(401);
            log.info("获取不到token被拦截..............");
            return false;
        }

        boolean validToken = JwtUtils.isValidToken(token, secret);
        if (!validToken) {
            //401:请求要求身份验证。 对于需要登录的网页，服务器可能返回此响应
            response.setStatus(401);
            log.info("token不合法被拦截..............");
            return false;
        }
        User user = JwtUtils.parseToken(token, secret);
        UserHolder.setUser(user);
        UserHolder.setToken(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从当前线程上删除user
        UserHolder.removeUser();
        UserHolder.removeToken();
//        log.info("已从当前线程上清除user和token信息");
    }
}
